package org.example.day12;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 4.2.2 类ReentrantReadWriteLock 的使用: 写写互斥
 */
public class MyThread5 {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public void read(){
        try {
            //获取写锁
            lock.writeLock().lock();
            System.out.println("获得写锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
            System.out.println("释放写锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
        }
    }
    public static void main(String[] args) {
        MyThread5 m5 = new MyThread5();
        Thread5A ta = new Thread5A(m5);
        ta.setName("A");
        Thread5B tb = new Thread5B(m5);
        tb.setName("B");
        ta.start();
        tb.start();
    }
}

class Thread5A extends Thread{
    private MyThread5 m5;

    public Thread5A(MyThread5 m5) {
        this.m5 = m5;
    }

    @Override
    public void run() {
        m5.read();
    }
}
class Thread5B extends Thread{
    private MyThread5 m5;

    public Thread5B(MyThread5 m5) {
        this.m5 = m5;
    }

    @Override
    public void run() {
        m5.read();
    }
}